package com.tpsix.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tpsix.domain.SysTenant;
import com.tpsix.service.SysTenantService;
import com.tpsix.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;


@Api(value = "tenants", tags = "租户资源")
@RestController
@RequestMapping("tenants")
@AllArgsConstructor
public class SysTenantResource {

    private final SysTenantService sysTenantService;

    @PreAuthorize("hasAuthority('sys:tenant:view')")
    @ApiOperation(value = "租户分页列表")
    @GetMapping("page")
    public R<Page<SysTenant>> page(Page<SysTenant> page, SysTenant tenant) {
        Page<SysTenant> pages = sysTenantService.page(page, Wrappers.query(tenant));
        return R.ok(pages);
    }

    @GetMapping
    @ApiOperation(value = "租户列表")
    public R<List<SysTenant>> list() {
        return R.ok(sysTenantService.list(Wrappers.<SysTenant>lambdaQuery().ge(SysTenant::getEndTime, LocalDateTime.now())));
    }

    @PreAuthorize("hasAuthority('sys:tenant:add')")
    @ApiOperation(value = "添加租户")
    @PostMapping
    public R<Void> add(@RequestBody SysTenant tenant) {
        sysTenantService.saveTenant(tenant);
        return R.ok();
    }

    @PutMapping
    @ApiOperation(value = "修改租户")
    @PreAuthorize("hasAuthority('sys:tenant:update')")
    public R<Void> update(@RequestBody SysTenant tenant) {
        tenant.setUpdateTime(LocalDateTime.now());
        sysTenantService.updateTenant(tenant);
        return R.ok();
    }

    @DeleteMapping("{id:\\d+}")
    @ApiOperation(value = "删除租户")
    @PreAuthorize("hasAuthority('sys:tenant:delete')")
    public R<Void> delete(@PathVariable int id) {
        sysTenantService.removeById(id);
        return R.ok();
    }

}
